from django.db import models
import zlib
import simplejson

# Create your models here.

class Request(models.Model):
    # Request
    scheme = models.CharField(max_length=16)
    path = models.TextField(max_length=2048)
    query = models.TextField(max_length=2048)
    method = models.TextField(max_length=32)
    body = models.TextField(max_length=4096)
    headers = models.TextField(max_length=1024)

    def sid(self):
        return str(self.id)


class Response(models.Model):
    uuid = models.CharField(max_length=128, primary_key=True)
    # Request
    request = models.ForeignKey(Request)
    # Reponse
    content = models.TextField(max_length=4096, blank=True)
    status = models.SmallIntegerField()

    def sid(self):
        return str(self.id)


class Status(models.Model):
    mapping = models.TextField(max_length=4096)

    def get_mapping(self):
        json = zlib.decompress(self.mapping)
        ret = simplejson.loads(json)
        return ret

    def set_mapping(self, mapping):
        json = simplejson.dumps(mapping)
        self.mapping = zlib.compress(json)
        self.save()


class Trigger(models.Model):
    trigger = models.ForeignKey(Request)
    prev_status = models.ForeignKey(Status, related_name="forward_triggers")
    next_status = models.ForeignKey(Status, related_name="backward_triggers")

    class Meta:
        unique_together = (('trigger', 'prev_status'),)

    def sid(self):
        return str(self.id)
